<!-- 想定编辑模块页面 -->
<template>
  <div class="scenario-edit-container">
    <div class="s-e-main flex flex-row">
      <div class="s-e-left flex flex-col">
        <Tree ref="scenarioDataTreeRef" :isGeneralFolderAndFile="true" :topAdd="true"
          :defaultExpandedKeys="defaultExpandedKeys" :currentNodeKey="currentNodeKey" :treeData="scenarioDataList"
          :topAddMenu="right_menuList.rightMenuList_1" :folderMenu="right_menuList.rightMenuList_2"
          :fileMenu="right_menuList.rightMenuList_3" @handleMenuClick="handleMenuClick"
          @nodeClick="nodeClick" @moveNodeOrder="moveNodeOrder"></Tree>
      </div>
      <div class="s-e-divider"></div>
      <div class="s-e-right">
        <FolderDetail v-if="isFolder" ref="folderRef" :nodeInfo="selectedNodeInfo" @refresh="getScenarioTree">
        </FolderDetail>
        <ScenarioDetail v-if="isFile" ref="scenarioDetailRef" :nodeInfo="selectedNodeInfo" @refresh="getScenarioTree">
        </ScenarioDetail>
      </div>
    </div>
    <AddOrUpdateFolder ref="addOrUpdateFolderRef" @refresh="getScenarioTree"></AddOrUpdateFolder>
    <AddOrUpdateFile ref="addOrUpdateFileRef" @refresh="getScenarioTree"></AddOrUpdateFile>
  </div>
</template>

<script>

import {
  getScenarioTree,
  delScenario,
  moveScenarioTree
} from "@/api/myspace/scenario-edit-tool/scenario-edit";
import { mapState } from "vuex";
import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";
import AddOrUpdateFile from "./components/add-or-update-file.vue";
import FolderDetail from "./components/folder-detail.vue";
import ScenarioDetail from "./components/scenario-detail.vue";
export default {
  name: "ScenarioEdit",
  data() {
    return {
      queryContent: "",
      activeName: null,
      mainVersionInfo: null,
      isFolder: false, // 是否展示文件夹详情
      isFile: false, // 是否展示文件详情
      selectedNodeInfo: {}, // 当前选中节点的信息
      scenarioDataList: [], // 想定数据列表
      defaultExpandedKeys: [], //树默认要展开的节点
      currentNodeKey: null,
      isFilterOpen: false,
      filters: {
        status: "",
        tags: "",
        owner: "",
        creator: "",
        lastModifier: "",
        matchType: "include",
      },
    };
  },
  components: {
    Tree,
    FolderDetail,
    ScenarioDetail,
    AddOrUpdateFolder,
    AddOrUpdateFile
  },
  computed: {
    ...mapState({
      right_menuList: (state) => state.scenarioEditTool.right_menuList,
      userId: (state) => state.user.id,
      selectedNodeId: (state) => state.scenarioEditTool.selectedNodeId,
      expandedNodeIds: (state) => state.scenarioEditTool.expandedNodeIds,
    }),
    filterNum() {
      return Object.values(this.filters).filter((item) => item).length - 1;
    },
  },
  async created() {
    await this.getScenarioTree();
    this.currentNodeKey = this.selectedNodeId;
    this.defaultExpandedKeys = this.expandedNodeIds;
    this.$nextTick(() => {
      this.$refs.scenarioDataTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
    })
  },
  mounted() {
  },
  methods: {
    async getScenarioTree(newNodeId) {
      await getScenarioTree().then((response) => {
        if (response.code != 200) return;
        this.scenarioDataList = response.data[0].commonTreeList;
        const targetId = newNodeId || this.selectedNodeId;
        const targetnode = targetId ? this.recurNodeForTarget(this.scenarioDataList, targetId) : this.scenarioDataList[0];
        this.nodeClick(targetnode);
      });
    },

    // 递归获取当前树节点
    recurNodeForTarget(nodeArr, id) {
      for (let i = 0; i < nodeArr.length; i++) {
        if (nodeArr[i].id == id) {
          return nodeArr[i];
        } else {
          if (nodeArr[i].children && nodeArr[i].children.length > 0) {
            let node = this.recurNodeForTarget(nodeArr[i].children, id);
            if (node) {
              return node;
            }
          }
        }
      }
    },
    //显示筛选条件
    openFilter() {
      this.isFilterOpen = !this.isFilterOpen;
    },
    // 点击菜单项触发的事件
    handleMenuClick(menu, node) {
      switch (menu.name) {
        case "新增分类":
        case "添加子目录":
          this.handleAddOrUpdateFolder("add", node);
          break;
        case "编辑目录":
          this.handleAddOrUpdateFolder("edit", node);
          break;
        case "新增想定":
          this.handleAddOrUpdateFile("add", node);
          break;
        case "编辑":
          this.handleAddOrUpdateFile("edit", node);
          break;
        case "复制":
          this.handleCopyFile(node);
          break;
        case "删除":
          this.handleDeleteFile(node);
          break;

      }
    },

    /**
     * 新增或修改文件
     * @param sign add/edit
     * @param node node
     */
    handleAddOrUpdateFile(sign, node) {
      this.$refs.addOrUpdateFileRef.init(
        sign,
        node,
      );
    },

    // 新增或修改文件夹
    handleAddOrUpdateFolder(sign, node) {
      this.$refs.addOrUpdateFolderRef.init(
        sign,
        node,
        this.scenarioDataList
      );
    },
    // 删除文件夹或文件
    handleDeleteFile(node) {
      let nodeTypeText = node.type === 0 ? "目录" : "想定";
      this.$confirm(`确定删除${nodeTypeText}  ${node.name} ?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "message-box-style",
        type: "warning",
      })
        .then(() => {
          delScenario(
            node.id
          ).then((response) => {
            if (response.code != 200) return;
            this.$message.success(
              this.$toolHandle.getI18nName(
                this.$zh.setup.responseText,
                this.$en.setup.responseText,
                this.$i18n.locale,
                "success"
              )
            );
            if (node.id == this.currentNodeKey) {
              this.isFolder = false;
              this.isFile = false;
            }
            this.getScenarioTree();
          });
        })
        .catch(() => { });
    },
    nodeClick(node) {
      if (node == undefined) return;
      this.selectedNodeInfo = node;
      this.currentNodeKey = node.id;
      this.$nextTick(() => {
        this.$refs.scenarioDataTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
      })
      this.$store.commit("scenarioEditTool/SET_SELECTED_NODE_ID", node.id)
      if (node.type == 0) {
        // 点击的文件夹
        this.isFolder = true;
        this.isFile = false;
        this.$store.commit("scenarioEditTool/SET_EXPANDED_NODE_IDS", Array.from(new Set([...this.defaultExpandedKeys, node.id])))
      } else {
        // 点击的文件
        this.isFolder = false;
        this.isFile = true;
      }
    },
    // 移动树节点的顺序
    moveNodeOrder(draggingNode, dropNode, dropType) {
      moveScenarioTree({
        movedNodeId: draggingNode.data.id, // 被移动节点的id
        referenceNodeId: dropNode.data.id, // 参照节点的id
        position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
        ancestors: draggingNode.data.data.ancestors, // 祖先
        folderChildrenOrder: {
          parentId:
            dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
          siblingIds:
            dropType == "inner"
              ? Array.from(dropNode.childNodes).map((item) => item.data.id)
              : Array.from(dropNode.parent.childNodes).map(
                (item) => item.data.id
              ),
        },
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getScenarioTree();
        }
      });
    },
    // 使用自定义数据，弹框，选择模型，选择版本，选择数据结构
    handleUseCustomData(node) {
      this.isUseCustomData = true;
      this.$nextTick(() => {
        this.$refs.useCustomDataRef.init();
      });
    },
    // 导入jsonschema文件
    handleImportFile(node) {
      this.selectedNodeInfo = node;
    },
  },
};
</script>

<style lang="scss" scoped>
.mm-l-tree-header {
  height: 40px;
  line-height: 40px;
  padding-left: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: var(--ui-text-color);
  border-bottom: 1px solid var(--ui-border-color-split);

  .icon-box {
    height: 32px;
    visibility: hidden;
  }

  &:hover {
    .icon-box {
      visibility: visible;

      .item-icon {
        width: 32px;
        height: 100%;

        &:hover {
          background-color: var(--ui-btn-text-hover-bg);
          border-radius: 6px;
        }
      }
    }
  }
}

.scenario-edit-container {
  width: 100%;
  height: 100%;
  padding: 0 10px;
  box-sizing: border-box;

  .s-e-main {
    width: 100%;
    height: 100%;

    .s-e-left {
      width: 300px;
      height: 100%;
      flex-grow: 0;
      flex-shrink: 0;
      display: flex;
      padding: 10px 10px 0 0;
      overflow: auto;

      .filer-box {
        display: flex;
        flex-wrap: wrap;
        transition: all 0.5s;

        .filter-item {
          width: 50%;
          padding: 5px 5px 0 0;

          .el-radio-group {
            display: flex;
          }
        }
      }

      .tree-box {
        flex-grow: 1;
        margin-top: 5px;
        box-sizing: border-box;
      }
    }

    .s-e-divider {
      width: 1px;
      height: 100%;
      flex-grow: 0;
      align-self: stretch;
      background-color: var(--ui-border-color-split);
    }

    .s-e-right {
      width: 256px;
      height: 100%;
      min-width: 0px;
      flex-grow: 1;
      flex-shrink: 1;
      display: flex;
      overflow: auto;
    }
  }
}
</style>